package com.teichmann.services;

import java.sql.Date;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.teichmann.bo.Car;
import com.teichmann.jpa.util.EntityManagerHelper;

public class CarServices {

	public static int updateFoundCars(List<Car> cars) {

		EntityManager em = EntityManagerHelper.getEntityManager().createEntityManager();

		Query queryUrl = em.createNamedQuery("Car.findByURL");
		em.getTransaction().begin();
		for (Car car : cars) {
			// discover if the car already exists in database.
			Collection<Car> carReturned = null;
			
			if ( (carReturned =queryUrl.setParameter(1, car.getUrl()).getResultList()).size() == 0) {
				em.persist(car);
			}
			else{ //update it
				Car updated =((List<Car>)carReturned).get(0);
				updated.setDataAtualizacao(new Date(System.currentTimeMillis()));
				em.merge(updated);
			}

		}
		em.getTransaction().commit();
		em.close();

		return cars.size();

	}
}
